Python Tuples
π Python Tuples: The Chill Cousins of Lists πβ
In Python-land, a tuple is like that chill friend who doesnβt change their mind. Think of it as a listβ¦ but with a βdo not disturbβ sign! π«βοΈ
Tuples are:
- β Immutable (Once you make it, you can't shake it!)
- π Ordered (It remembers its position)
- π Heterogeneous (Mix 'n match any data types!)
- π’ Indexed (Starts at 0, as usual)
- π₯ (Optionally) Parenthesized (Parentheses are optional, but preferred β like wearing socks with shoes)
- β‘ Fast when looping (because theyβre low-maintenance)
Tuples are great when you want to pack related stuff together like... employee info! π©βπΌπ¨βπΌ
π¬ 1. Creating a Tupleβ
Letβs roll!
tuple1 = () # empty tuple
tuple2 = (1, "2", 3.0)
tuple3 = 1, "2", 3.0 # parentheses are optional
π― 1.1. Tuple with One Itemβ
Beware: Without a trailing comma, Python thinks you're just being dramatic with brackets!
not_a_tuple = ("hello") # Just a string
tuple_with_one = ("hello",) # Now thatβs a tuple!
π 1.2. Nested Tuplesβ
Tuples within tuples β like inception but in Python.
nested_tuple = ("hello", ("python", "world"))
π 2. Accessing Tuple Itemsβ
Use indices inside square brackets. Pythonβs counting starts at zero. Letβs do a mini treasure hunt! πΊοΈ
Tuple = ("a", "b", "c", "d", "e", "f")
print(Tuple[0]) # 'a'
print(Tuple[-1]) # 'f'
print(Tuple[0:3]) # ('a', 'b', 'c')
Tuple = ("a", "b", "c", ("d", "e", "f"))
print(Tuple[3][1]) # 'e'
π 3. Looping through Tuplesβ
Simple as pie π₯§
Tuple = ("a", "b", "c")
for item in Tuple:
print(item)
β 4. Existence Checkβ
Check if an item exists with in
or not in
β your tupleβs bouncer at the club π·
Tuple = ("a", "b", "c")
if "a" in Tuple:
print("Yup, 'a' is in the house!")
if "x" not in Tuple:
print("'x' got denied at the tuple-door.")
π§Ό 5. Sorting a Tupleβ
Want to sort your tuple? Use sorted()
to keep things neat (note: returns a list, not a tuple!).
Tuple = ("a", "c", "b", "e", "d")
sortedTuple = sorted(Tuple)
print(sortedTuple) # ['a', 'b', 'c', 'd', 'e']
π 6. Repetition & Concatenationβ
Multiply or add tuples like a magician π©β¨
Tuple = ("a", "b")
print(Tuple * 3) # ('a', 'b', 'a', 'b', 'a', 'b')
Tuple1 = ("a", "b")
Tuple2 = ("c", "d")
print(Tuple1 + Tuple2) # ('a', 'b', 'c', 'd')
π 7. Packing & Unpacking Tuplesβ
Packing: wrapping gifts π
Unpacking: opening them π
Tuple = ("a", "b", "c") # Packing
x, y, z = Tuple # Unpacking
print(x) # 'a'
print(y) # 'b'
print(z) # 'c'
β οΈ Warning: Mismatched items will throw a tantrum (a.k.a. ValueError)
π©βπ¬ 8. Named Tuples (Supercharged Tuples!)β
NamedTuples from collections
are like tuples with name tags! πΌ
import collections
Record = collections.namedtuple('Record', ['id', 'name', 'date'])
r1 = Record('1', 'RecordName', '12/12/2020')
print(r1[0]) # '1'
print(r1.name) # 'RecordName'
π οΈ 9. Tuple Utility Methodsβ
Letβs bring out the tuple toolbox π§°
β
9.1 any()
β
print(any(())) # False
print(any((1,))) # True
π 9.2 min()
& 9.3 max()
β
Tuple = (4, 1, 9)
print(min(Tuple)) # 1
print(max(Tuple)) # 9
π 9.4 len()
β
print(len(Tuple)) # 3
β 9.5 sum()
β
print(sum(Tuple)) # 14
π 10. Conclusionβ
Tuples are:
- π§± Immutable (canβt be changed)
- π§ Ordered and Indexed
- π¨ Heterogeneous
- π Faster for iteration
NamedTuples = Tuples + Superpowers.
Tuples = Lists but stricter, faster, and cooler π
Happy Tuple-ing! ππ